import { computed, onMounted, ref, watch } from "vue";
import { cloneDeep } from "lodash-es";

export const matrixInputProps = {
  value: {
    type: Object,
    default: () => {}
  },
  table: {
    type: Object,
    default: () => {}
  }
};

export function useMatrixInput(props: any, emit: any) {
  const dataValue = ref<any>({});
  const loading = ref(true);

  // 初始化矩阵value为二维数组
  const initValue = (value: any) => {
    let cloneValue = cloneDeep(value);
    if (value) {
      dataValue.value = cloneValue;
    } else {
      dataValue.value = {};
    }
    let initValue: Record<string, Record<string, any>> = {};
    props.table.rows.forEach((row: any) => {
      initValue[row.id] = {};
      props.table.columns.forEach((col: any) => {
        if (value && value[row.id] && value[row.id][col.id]) {
          initValue[row.id][col.id] = value[row.id][col.id];
        } else {
          initValue[row.id][col.id] = null;
        }
      });
    });
    dataValue.value = initValue;
    loading.value = false;
  };

  const getTableRows = computed(() => {
    return props.table.rows;
  });

  onMounted(() => {
    initValue(props.value);
  });

  const handleChange = (val: any) => {
    emit("update:value", dataValue.value);
    emit("change", dataValue.value);
  };

  watch(
    () => props.table,
    () => {
      initValue(props.value);
    },
    { deep: true }
  );

  watch(
    () => props.value,
    val => {
      initValue(val);
    },
    { deep: true }
  );

  return {
    initValue,
    getTableRows,
    handleChange,
    dataValue,
    loading
  };
}
